package gov.kqqzyyy.monkey.pharmacyscreen.code.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import gov.kqqzyyy.monkey.pharmacyscreen.R;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.MyServiceUtil;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.ProgressDialogFragment;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.UpdateInfo;

import gov.kqqzyyy.monkey.pharmacyscreen.code.object.YFCK;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.YFLB;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.YF_YFCK;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@SuppressWarnings("ALL")
public class FragmentPreferences extends Activity {

    private List<YF_YFCK> mResultList;

    private ProgressDialogFragment progressDialogFragment;

    private Call<String> yfckCall;

    private PrefsFragement prefsFragement;

    private CountDownTimer yfckTimer;

//    private BaseObserver<List<YF_YFCK>> yfckObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        doGetYFCK();
//        doGetYfck_New();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (yfckCall != null && yfckCall.isExecuted()) {
            yfckCall.cancel();
        }
        if (prefsFragement != null && prefsFragement.serverTestThread != null && prefsFragement.serverTestThread.isAlive()) {
            prefsFragement.serverTestThread.interrupt();
            prefsFragement.serverTestThread = null;
        }
        if (yfckTimer != null) {
            yfckTimer.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    public List<YF_YFCK> getmResultList() {
        return mResultList;
    }

    // 设置类
    public static class PrefsFragement extends PreferenceFragment implements Preference.OnPreferenceChangeListener {

        SharedPreferences mSharedPreferences;
        ListPreference mPharmacyPreference; //药方列表
        ListPreference mWindowPreference; //窗口列表
        ListPreference mWindowDetailPreference;//自煎窗口细分
        EditTextPreference mServerAddPreference; //服务器地址

        List<YF_YFCK> mResultList;
        List<String> yfmcList;//药房名称
        List<String> yfsbList;//药房识别
        List<String> ckmcList;//窗口名称
        List<String> cksbList;//窗口识别
        String defaultPharmacy;
        String preServerAdd;

        MyHandler myHandler;
        Thread serverTestThread;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mSharedPreferences = getPreferenceManager().getSharedPreferences();
            myHandler = new MyHandler((FragmentPreferences) getActivity());
            addPreferencesFromResource(R.xml.preferences);//从XML文件加载选项
            onBindXML();

            setAddressText();
            mServerAddPreference.setOnPreferenceChangeListener(this);

            mResultList = ((FragmentPreferences) getActivity()).getmResultList();
            yfmcList = new ArrayList<>();
            yfsbList = new ArrayList<>();

            for (YF_YFCK yf_yfck : mResultList
            ) {
                yfmcList.add(yf_yfck.getYflb().getYfmc());
                yfsbList.add(String.valueOf(yf_yfck.getYflb().getYfsb()));
            }
            CharSequence[] yfmcArray = yfmcList.toArray(new CharSequence[yfmcList.size()]);
            CharSequence[] yfsbArray = yfsbList.toArray(new CharSequence[yfsbList.size()]);
            mPharmacyPreference.setEntries(yfmcArray);
            mPharmacyPreference.setEntryValues(yfsbArray);

            mPharmacyPreference.setOnPreferenceChangeListener(this);

            mWindowPreference.setOnPreferenceChangeListener(this);
            mWindowPreference.setSummary(mSharedPreferences.getString("window_name", ""));

            mWindowDetailPreference.setOnPreferenceChangeListener(this);

            defaultPharmacy = mSharedPreferences.getString("pharmacy_preference", "");
            if (!defaultPharmacy.equals("")) {
                setYFCKArray(defaultPharmacy);
                mPharmacyPreference.setSummary(yfmcArray[yfsbList.indexOf(defaultPharmacy)]);
            }
            setDetailWindow();
        }

        private void setAddressText() {
            preServerAdd = mSharedPreferences.getString("server_address", getString(R.string.default_server));
            mServerAddPreference.setText(preServerAdd);
            mServerAddPreference.setSummary(preServerAdd);
        }

        private void onBindXML() {
            mServerAddPreference = (EditTextPreference) findPreference("server_address");
            mPharmacyPreference = (ListPreference) findPreference("pharmacy_preference");
            mWindowPreference = (ListPreference) findPreference("window_preference");
            mWindowDetailPreference = (ListPreference) findPreference("window_detail_preference");
        }

        private void setYFCKArray(String yfsb) {
            for (YF_YFCK yf_yfck : mResultList
            ) {
                if (String.valueOf(yf_yfck.getYflb().getYfsb()).equals(yfsb)) {
                    List<YFCK> yfckList = yf_yfck.getYfck();
                    ckmcList = new ArrayList<>();
                    cksbList = new ArrayList<>();
                    for (YFCK yfck : yfckList) {
                        ckmcList.add(yfck.getCKMC());
                        cksbList.add(yfck.getCKBH());
                    }
                    CharSequence[] ckmcArray = ckmcList.toArray(new CharSequence[ckmcList.size()]);
                    CharSequence[] cksbArray = cksbList.toArray(new CharSequence[cksbList.size()]);
                    mWindowPreference.setEntries(ckmcArray);
                    mWindowPreference.setEntryValues(cksbArray);
                    String mCKSB = mSharedPreferences.getString("window_preference", "");
                    if (!mCKSB.equals("")) {
                        mWindowPreference.setValue(mCKSB);
                        mWindowPreference.setSummary(ckmcArray[cksbList.indexOf(mCKSB)].toString());
                    } else {
                        mWindowPreference.setValue(cksbArray[0].toString());
                        mWindowPreference.setSummary(ckmcArray[0].toString());
                        mSharedPreferences.edit().putString("window_preference", cksbArray[0].toString()).apply();
                        mSharedPreferences.edit().putString("window_name", ckmcArray[0].toString()).apply();
                    }
                    setDetailWindow();
                }
            }
        }

        //设置细分窗口默认值
        private void setDetailWindow() {
            if (mSharedPreferences.getString("pharmacy_preference", "").equals("2") && mSharedPreferences.getString("window_name", "").equals("自煎窗口")) {
                mWindowDetailPreference.setEnabled(true);
                CharSequence[] detailWindowValue = getResources().getStringArray(R.array.pharmacy_window_detail_entryvalues);
                CharSequence[] detailWindowName = getResources().getStringArray(R.array.pharmacy_window_detail_entries);
                String detailWindow = mSharedPreferences.getString("window_detail_preference", "");
                if (!detailWindow.equals("")) {
                    String summaryName = "";
                    for (int i = 0; i < detailWindowValue.length; i++) {
                        if (detailWindowValue[i].toString().equals(detailWindow)) {
                            summaryName = detailWindowName[i].toString();
                            break;
                        }
                    }
                    mWindowDetailPreference.setSummary(summaryName);
                    mWindowDetailPreference.setValue(detailWindow);
                } else {
                    mWindowDetailPreference.setSummary(detailWindowName[0]);
                    mWindowDetailPreference.setValue(detailWindowValue[0].toString());
                }
            } else {
                mWindowDetailPreference.setEnabled(false);
            }
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                CharSequence[] entries = listPreference.getEntries();
                int index = listPreference.findIndexOfValue((String) newValue);
                listPreference.setSummary(entries[index]);
                if (preference.getKey().equals("pharmacy_preference")) {
                    boolean isChanged = !newValue.toString().equals(defaultPharmacy);
                    if (isChanged) {
                        defaultPharmacy = newValue.toString();
                        mSharedPreferences.edit().putString("pharmacy_name", (String) entries[index]).apply();
                        mSharedPreferences.edit().putString("window_preference", "").apply();
                        setYFCKArray(defaultPharmacy);
                    }

                } else if (preference.getKey().equals("window_preference")) {
                    mSharedPreferences.edit().putString("window_name", (String) entries[index]).apply();
                    setDetailWindow();
                }
            } else {
                ((FragmentPreferences) getActivity()).showProgressDialog("服务器连接测试中");
                final String newAdd = newValue.toString();
                serverTestThread = new Thread(() -> {
                    Message message = new Message();
                    if (UpdateInfo.isServerAvailable(newAdd)) {
                        message.what = 0x11;
                    } else {
                        message.what = 0x12;
                        mSharedPreferences.edit().putString("server_address", preServerAdd).apply();
                    }
                    myHandler.sendMessage(message);
                    serverTestThread.interrupt();
                    serverTestThread = null;
                });
                serverTestThread.start();
            }
            return true;
        }

    }

    private static class MyHandler extends Handler {
        WeakReference<FragmentPreferences> mActivity;

        MyHandler(FragmentPreferences activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FragmentPreferences activity = mActivity.get();
            activity.cancelProgressDialog();
            switch (msg.what) {
                case 0x11:
                    Toast.makeText(activity, "服务器连接成功,重启该界面", Toast.LENGTH_SHORT).show();
                    activity.doRestart();
                    break;
                case 0x12:
                    Toast.makeText(activity, "服务器连接失败，重置默认地址", Toast.LENGTH_SHORT).show();
                    break;
            }
            activity.prefsFragement.setAddressText();
        }
    }

    private void doRestart() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

   /* private void doGetYfck_New() {
//        showProgressDialog("获取药房窗口列表中_2");
        Observable<BaseResponse<List<YF_YFCK>>> observable = RetrofitUtil.getInstence().getYfckList();
        yfckObserver = new BaseObserver<List<YF_YFCK>>() {
            @Override
            protected void onSuccees(BaseResponse<List<YF_YFCK>> result) {
//                cancelProgressDialog();
                mResultList = result.getData();
                if (mResultList != null && mResultList.size() > 0) {
                    Toast.makeText(getApplicationContext(), "获取药房窗口成功！", Toast.LENGTH_LONG).show();
                } else {
                    timeToGetYFCK();
                }
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
//                cancelProgressDialog();
                KLog.d("APE", e);
            }

            @Override
            protected void onCodeError(BaseResponse<List<YF_YFCK>> t) {
                super.onCodeError(t);
//                cancelProgressDialog();
                KLog.d("APE", t);
            }
        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(yfckObserver);
    }*/

    private void doGetYFCK() {
        showProgressDialog("获取药房窗口列表中");
        yfckCall = MyServiceUtil.getYFCKCall();
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                cancelProgressDialog();
                Gson gson = new Gson();
                String result = response.body();
                if (result != null) {
                    mResultList = gson.fromJson(result, new TypeToken<List<YF_YFCK>>() {
                    }.getType());
                    if (mResultList != null && mResultList.size() > 0) {
                        addJKCK();
                        prefsFragement = new PrefsFragement();
                        getFragmentManager().beginTransaction().replace(android.R.id.content, prefsFragement).commit();
                    }
                } else {
                    timeToGetYFCK();
//                    showEmptyChoose();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                cancelProgressDialog();
                timeToGetYFCK();
                Toast.makeText(getApplicationContext(), "获取药房窗口失败 " + t.toString(), Toast.LENGTH_LONG).show();
            }
        };
        yfckCall.enqueue(callback);
    }

    private void timeToGetYFCK() {
//        Toast.makeText(getApplicationContext(), "获取药房窗口失败,即将重新获取 ", Toast.LENGTH_SHORT).show();
        yfckTimer = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                doGetYFCK();
//                doGetYfck_New();
            }
        };
        yfckTimer.start();
    }

//    private void showEmptyChoose() {
//        Toast.makeText(getApplicationContext(), "获取药房窗口失败 ", Toast.LENGTH_SHORT).show();
//        mResultList = new ArrayList<>();
//        PrefsFragement prefsFragement = new PrefsFragement();
//        FragmentManager fragmentManager = getFragmentManager();
//        if (fragmentManager != null) {
//            fragmentManager.beginTransaction().replace(android.R.id.content, prefsFragement).commit();
//        }
//
//    }

    private void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    private void showProgressDialog(String message) {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage(message);
        progressDialogFragment.show(getFragmentManager(), "downLoading");
    }

    private void addJKCK() { //西药房添加叫号窗口
        YFCK yfck = new YFCK();
        yfck.setCKBH("0.0");
        yfck.setCKMC("叫号");
        for (YF_YFCK yfYfck : mResultList) {
            YFLB yflb = yfYfck.getYflb();
            if (yflb.getYfmc().equals("西药房")) {
                List<YFCK> yfckList = yfYfck.getYfck();
                yfckList.add(yfck);
                return;
            }
        }
    }

}